#define  _CRT_SECURE_NO_WARNINGS 1
#include "stack.h"

int GetMid(int* a, int left, int right)
{
	int mid = (left + right) >> 1;
	if (a[mid] > a[left])
	{
		if (a[right] > a[mid])
			return mid;
		else
			return a[left] > a[right] ? left : right;
	}
	else
	{
		if (a[mid] > a[right])
			return mid;
		else
			return a[left] > a[right] ? right : left;
	}
}

void swap(int* a, int* b)
{
	int tmp = *a;
	*a = *b;
	*b = tmp;
}

int PartSort(int* a, int left, int right)
{
	int index = GetMid(a, left, right);
	swap(&a[left], &a[index]);
	int prev = left;
	int curr = left + 1;
	int k = left;
	while (curr <= right)
	{
		if (a[curr] < a[k] && ++prev != curr)
			swap(&a[curr], &a[prev]);
		curr++;
	}
	swap(&a[prev], &a[k]);
	return prev;
}

void QuickSortNonR(int* a, int n)
{
	Stack st;
	StackInit(&st);
	StackPush(&st, n - 1);
	StackPush(&st, 0);
	while (!StackEmpty(&st))
	{
		int left = StackTop(&st);
		StackPop(&st);
		int right = StackTop(&st);
		StackPop(&st);
		int index = PartSort(a, left, right);
		if (left < index-1)
		{
			StackPush(&st, index - 1);
			StackPush(&st, left);
		}
		if (index + 1 < right)
		{
			StackPush(&st, right);
			StackPush(&st, index+1);
		}
	}
	StackDestory(&st);
}



void MergeSortNonR(int* a, int n)
{
	int* tmp = (int*)malloc(sizeof(int) * n);
	for (int gap = 1; gap < n; gap *= 2)
	{
		for (int i = 0; i < n; i += 2 * gap)
		{
			int begin1 = i;
			int end1 = i + gap - 1;
			int begin2 = i + gap;
			int end2 = i + 2 * gap - 1;
			int index = i;
			if (begin2 > n)
				break;
			if (end2 > n)
				end2 = n - 1;
			while (begin1 <= end1 && begin2 <= end2)
			{
				if (a[begin1] > a[begin2])
					tmp[index++] = a[begin2++];
				else
					tmp[index++] = a[begin1++];
			}
			while (begin1 <= end1)
				tmp[index++] = a[begin1++];
			while (begin2 <= end2)
				tmp[index++] = a[begin2++];
			for (int j = i; j <= end2; j++)
			{
				a[j] = tmp[j];
			}
		}
	}
	free(tmp);
}